本日目標:
首先,我們要開通chrome.contextMenus
manifest.json
"permissions": [
"activeTab",
"alarms",
"contextMenus"
]
然後在後台腳本中新增一個Class專門管理contentMenus
class MenuManager{
constructor(){
this.menus = {
startAlarm: {
id: 'startAlarm',
title: '開始番茄鐘',
contexts: ['browser_action'],
enabled: true,
},
stopAlarm: {
id: 'stopAlarm',
title: '停止番茄鐘',
contexts: ['browser_action'],
enabled: false,
},
pauseAlarm: {
id: 'pauseAlarm',
title: '暫停番茄鐘',
contexts: ['browser_action'],
enabled: false,
}
}
//監控點擊事件
chrome.contextMenus.onClicked.addListener((info)=>{
this.onMenuClick(info)
})
//第一次載入
this.refreshByTimeState()
}
//當清單被點選時事件處理
onMenuClick(info){
switch (info.menuItemId) {
case 'startAlarm':
case 'pauseAlarm':
pomodoro.handleIconClick()
break;
case 'stopAlarm':
pomodoro.reset()
break;
}
}
//由番茄鐘呼叫更新清單與權限
refreshByTimeState(timeState = 'stop'){
if(timeState === 'start'){
this.menus.startAlarm.enabled = false
this.menus.stopAlarm.enabled = true
this.menus.pauseAlarm.enabled = true
}else if(timeState === 'pause'){
this.menus.startAlarm.enabled = true
this.menus.stopAlarm.enabled = true
this.menus.pauseAlarm.enabled = false
}else{
this.menus.startAlarm.enabled = true
this.menus.stopAlarm.enabled = false
this.menus.pauseAlarm.enabled = false
}
chrome.contextMenus.removeAll(()=>{ //可以清除所有的右鍵選單
Object.values(this.menus).forEach(menu=>{
chrome.contextMenus.create(menu) //新增選單
})
})
}
}
//全域宣告
var menuManager = new MenuManager()
由於現在有三種狀態了(開始,暫停,結束),所以我們要變更一下Pomodoro的設定
讓每種狀態切換的時候就去更新一下清單的狀態
class Pomodoro{
...
//將 this.isRun 更改為 this.alarmState
this.alarmState = 'stop' // start , pause , stop
//開始時鐘
start() {
this.timeState = 'start'
menuManager.refreshByTimeState(this.timeState)
chrome.alarms.create(ALARM_NAME, {
when: Date.now(),
periodInMinutes: 0.05
})
chrome.browserAction.setBadgeText({ text: String(this.time) + 'min' })
}
//暫停時鐘
pause() {
this.timeState = 'pause'
menuManager.refreshByTimeState(this.timeState)
chrome.browserAction.setBadgeText({ text: '-' })
chrome.alarms.clear(ALARM_NAME)
}
//重置時鐘
reset(){
this.timeState = 'stop'
menuManager.refreshByTimeState(this.timeState)
chrome.alarms.clear(ALARM_NAME)
chrome.browserAction.setBadgeBackgroundColor({ color: '#4285f4' })
chrome.browserAction.setBadgeText({ text: '-' })
this.workNum = 0
this.restNum = 0
this.time = this.workTime
this.timer = 'work'
}
...
}
登登,就來開啟頁面看一下吧,再載入功能時先按一次
然後在開始番茄鐘以後再按一次
然後點選「暫停番茄鐘」or再點一次icon暫停時鐘
看來功能正常喔!非常的順利,不過contentMenus還有很多很好玩的參數,可以去官網看一下喔
chrome.contextMenus